﻿/**
 * 同环比图
 */

export const buildChart = function (myChart, data, columnFields, rowFields, options) {
  // 如果用户输入数据不足直接退出
  if (!columnFields[0] || !rowFields[0]) {
    return;
  }
  let dimension = columnFields[0].slaveType === 0 ? columnFields[0] : rowFields[0];
  let measure = rowFields[0].slaveType === 1 ? rowFields[0] : columnFields[0];

  //提取X轴数据
  let categories = data.map(t => t[dimension.name])
  //日期自动排序
  if (dimension.slaveType === 4) {
    categories.sort();
  }
  let config = options.chartConfig;

  //图表间距
  let padding = [30, 10, 15, 10];
  if (config.chartPadding && config.chartPadding !== '') {
    let arrayPadding = config.chartPadding.split(' ');
    if (arrayPadding.length >= 4) {
      padding = arrayPadding.map(d => {
        return parseInt(d);
      });
    }
  }
  if (!config.showSplitLine && config.showSplitLine !== false) {
    config.showSplitLine = true;
  }
  let globalcolor = config.GlobalColor;
  //轴文字样式
  let axis_nameTextStyle = {
    color: config.axisStyle.fontColor,
    fontSize: config.axisStyle.fontSize,
    fontFamily: config.axisStyle.fontFamily
  }
  //数据条标签配置
  let labelOption = {
    normal: {
      show: config.textStyle["display"] !== "none",
      distance: 5,
      align: "left",
      verticalAlign: "middle",
      fontSize: config.textStyle["font-size"],
      fontFamily: config.textStyle["font-family"],
      color: config.textStyle["fill"],

    }
  };
  let labelOption_v = {
    normal: {
      show: config.textStyle["display"] !== "none",
      distance: 5,
      align: "left",
      verticalAlign: "middle",
      fontSize: config.textStyle["font-size"],
      fontFamily: config.textStyle["font-family"],
      color: config.textStyle["fill"],
      rotate: config.labelRotate
    }
  };

  //轴线配置
  let axis_axisLine = {
    lineStyle: {
      color: config.axisStyle.tickColor
    },
    show: config.showAxisLine == undefined ? true : config.showAxisLine
  }


  const option_chart = {
    color: config.MultiColors,
    legend: {
      data: [],
      textStyle: axis_nameTextStyle,
      show: config.showLegend == undefined ? true : config.showLegend,
      itemWidth: 14,
      itemHeight: 14
    },
    //toolbox: {
    //    show: true,
    //    orient: 'vertical',
    //    top: 'center',
    //    right: 10,
    //    feature: {
    //        mark: { show: true },
    //        saveAsImage: { show: true }
    //    },
    //    iconStyle: {
    //        borderColor: config.axisStyle.fontColor,
    //        textPosition: "left"
    //    }
    //},
    xAxis: [],
    yAxis: [],
    series: [],
    others: {
      dimensionField: dimension,
      measureField: measure,
      categories: categories,
      labelFormater: config.labelFormater,
      datamarking: options.DataMarking
    },
    grid: [{
      top: (config.showLegend == undefined || config.showLegend) ? 20 + padding[0] : padding[0],
      left: padding[3],
      bottom: padding[2],
      right: padding[1],
      containLabel: true
    }]
  };
  config.legendPosition = config.legendPosition || "top";
  if (config.legendPosition == "left") {
    option_chart.legend.x = "left";
  } else if (config.legendPosition == "right") {
    option_chart.legend.x = "right";
    option_chart.toolbox.left = 20;
  }
  option_chart.xAxis = [{
    type: 'category',
    //splitLine: {
    //    show: false
    //},
    //splitArea: {
    //    show: true,
    //},
    axisTick: {show: false},
    data: categories,
    //name: dimension.name,
    name: config.xAxisLabelRotate ? "" : dimension.name,
    nameTextStyle: axis_nameTextStyle,
    axisLine: axis_axisLine,
    axisLabel: {
      color: axis_nameTextStyle.color,
      fontSize: axis_nameTextStyle.fontSize,
      fontFamily: axis_nameTextStyle.fontFamily,
      interval: 0,
      fontWeight: "lighter",
      rotate: config.xAxisLabelRotate != undefined ? config.xAxisLabelRotate : 0,
      show: config.showAxisLabel ? config.showAxisLabel.category : true
    },
    nameLocation: "center",
    nameGap: config.axisStyle.fontSize * 1.8,
    gridIndex: 0
  }];
  if (config.xAxisName) {
    if (config.xAxisName.show) {
      if (config.xAxisName.name) {
        option_chart.xAxis[0].name = config.xAxisName.name;
      }
    } else {
      option_chart.xAxis[0].name = "";
    }
  }
  option_chart.yAxis = [
    {
      type: 'value',
      //splitLine: {
      //    show: false
      //},
      //splitArea: {
      //    show: true,
      //},
      name: measure.name,
      nameTextStyle: axis_nameTextStyle,
      axisLine: axis_axisLine,
      axisTick: axis_axisLine,
      axisLabel: {
        color: axis_nameTextStyle.color,
        fontSize: axis_nameTextStyle.fontSize,
        fontFamily: axis_nameTextStyle.fontFamily,
        show: config.showAxisLabel ? config.showAxisLabel.value : true
      },
      splitLine: {
        show: config.showSplitLine && (config.splitLineMode == undefined || config.splitLineMode == "all" || config.splitLineMode == "left"),
        lineStyle: {
          color: config.axisStyle.tickColor
        }
      },
      gridIndex: 0
    },
    {
      type: 'value',
      //splitLine: {
      //    show: false
      //},
      //splitArea: {
      //    show: true,
      //},
      name: '百分比',
      //min: -100,
      //max: 100,
      //axisLabel: {
      //    formatter: '{value} %',
      //},
      nameTextStyle: axis_nameTextStyle,
      axisLine: axis_axisLine,
      axisTick: axis_axisLine,
      splitLine: {
        show: config.showSplitLine && (config.splitLineMode == undefined || config.splitLineMode == "all" || config.splitLineMode == "right"),
        lineStyle: {
          color: config.axisStyle.tickColor
        }
      },
      axisLabel: {
        color: axis_nameTextStyle.color,
        fontSize: axis_nameTextStyle.fontSize,
        fontFamily: axis_nameTextStyle.fontFamily,
        formatter: '{value} %',
        show: config.showAxisLabel ? config.showAxisLabel.value2 : true
      },
      gridIndex: 0
    }
  ];
  if (config.yAxisName) {
    if (config.yAxisName.show) {
      if (config.yAxisName.name) {
        option_chart.yAxis[0].name = config.yAxisName.name;
      }
    } else {
      option_chart.yAxis[0].name = "";
    }
  }
  if (config.yAxisName2) {
    if (config.yAxisName2.show) {
      if (config.yAxisName2.name) {
        option_chart.yAxis[1].name = config.yAxisName2.name;
      }
    } else {
      option_chart.yAxis[1].name = "";
    }
  }
  //当前值、同比值、同比率、环比率
  //var groups = [
  //    { '当前值': measure.name },
  //    { '同比值': 'YoYValue' },
  //    { '同比率': 'YoYRate' },
  //    { '环比率': 'QoQRate' }
  //];
  let groups = {'本期': measure.name, '同期': 'YoYValue', '同比增长率': 'YoYRate', '环比增长率': 'QoQRate'};
  if (dimension.dataType !== 4) {
    //非日期
    groups = {'本期': measure.name, '同期': 'YoYValue', '同比增长率': 'YoYRate'};
  }
  if (!config.labelPosition || config.labelPosition == "foot") {
    labelOption_v.normal.position = "insideBottomLeft";
  } else {
    labelOption_v.normal.position = "insideTopLeft";
  }
  var _seriesIndex = 0;
  for (var group in groups) {
    var legend = group;
    option_chart.legend.data.push(legend);
    var measureKey = groups[group];
    var serieType = 'bar';
    var serie_yAxisIndex = 0;
    if (group === '同比增长率' || group === '环比增长率') {
      serieType = 'line';
      serie_yAxisIndex = 1;
    }
    var serie = {
      name: legend,
      type: serieType,
      yAxisIndex: serie_yAxisIndex,
      label: serieType === 'bar' ? labelOption_v : labelOption,
      //barGap: serieType === 'bar' ? '5%' : {},
      itemStyle: serieType === 'bar' ? {
        // 定制显示（按顺序）
        color: function (params) {
          //console.log(params);
          if (params.seriesType === "bar") {
            var color = config.MultiColors[params.seriesIndex];
            var c_data = params.data;
            if (params.seriesIndex === 0) {
              if (config.valley && config.valley.enable && c_data < config.valley.value) {
                color = config.valley.color;
              } else if (config.peak && config.peak.enable && c_data > config.peak.value) {
                color = config.peak.color;
              }
            }
            if (config.barFillStyle && Number(config.barFillStyle.mode) === 1) {
              return {
                type: 'linear',
                x: config.barFillStyle.gradientDirection === 'left' ? 1 : 0,
                y: config.barFillStyle.gradientDirection === 'top' ? 1 : 0,
                x2: config.barFillStyle.gradientDirection === 'right' ? 1 : 0,
                y2: config.barFillStyle.gradientDirection === 'bottom' ? 1 : 0,
                colorStops: [{
                  offset: 0, color: config.barFillStyle.gradientBeginColor // 0% 处的颜色
                }, {
                  offset: 1, color: color // 100% 处的颜色
                }],
                global: false // 缺省为 false
              }
            }
            return color;
          } else {
            //console.log(config.MultiColors[params.seriesIndex]);
            return config.MultiColors[params.seriesIndex];
          }
        }
      } : {
        color: config.MultiColors[_seriesIndex]
      },
      lineStyle: {
        color: config.MultiColors[_seriesIndex]
      },
      data: []
    }
    if (serieType === "bar") {
      serie.barMaxWidth = config.scale * 100 + "%";
      if (config.barBorderRadius) {
        serie.itemStyle.barBorderRadius = config.barBorderRadius;
      }
    }
    if (serieType == "line") {
      serie.smooth = config.lineSmooth;
    }
    option_chart.series.push(serie);
    categories.forEach(function (c) {
      var find = data.find(function (d) {
        return d[dimension.name] === c;
      });
      if (find) {
        var yoy = find[measureKey] || 0;
        if (legend === '同期') {
          serie.data.push(find[measure.name] - yoy);
        } else {
          serie.data.push(yoy);
        }
      } else {
        serie.data.push(0);
      }
    });
    _seriesIndex++;
  }
  ;

  const chartInstance = new chart(myChart, option_chart);
  return chartInstance;
}

const chart = function (myChart, opt) {
  var datamarkingopt = opt.others.datamarking;
  var datamarkingmapping = {}
  delete opt.others.datamarking;
  //处理数据脱敏
  if (datamarkingopt) {
    datamarkingopt.dimensions.forEach(function (dko) {
      if (dko.DataMarkingEnable) {
        datamarkingmapping[dko.name] = {
          mapping: {}
        }
        opt.others.categories.forEach(function (d) {
          var k = d.split("|")[0];
          datamarkingmapping[dko.name].mapping[k] = k.marking();
        });
      }
    });
  }
  var self = this;
  var _labelFormater = opt.others.labelFormater || "name:value";
  let chart_opt = {
    tooltip: {
      trigger: 'item',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (args) {
        if (args.componentSubType === "line") {
          return opt.others.dimensionField.name + "：" + args.name + "<br/>" + args.seriesName + "：" + Number(args.value).toFixed(2) + "%";
        } else {
          let dFieldValue = args.name;
          if (args.componentIndex && args.componentIndex === 1) {
            if (opt.others.dimensionField.dateTimeSub === 'year') {
              dFieldValue = args.name;
              dFieldValue = Number(dFieldValue) - 1;
            } else if (opt.others.dimensionField.dateTimeSub === '_ym' || opt.others.dimensionField.dateTimeSub === '_ymd') {
              dFieldValue = args.name;
              dFieldValue = (Number(dFieldValue.substring(0, 4)) - 1) + dFieldValue.substring(4);
            }
            dFieldValue += "（同期）";
          } else {
            dFieldValue += "（本期）";
          }
          return opt.others.dimensionField.name + "：" + dFieldValue + "<br/>" + opt.others.measureField.name + "：" + Number(args.value).toMeasureFormart(opt.others.measureField.numberFormat);
        }
      }
    }
  };
  const labelFormatter = args => {

    var result = _labelFormater.replace("name", args.seriesName);
    if (args.seriesName.includes("增长率")) {
      result = result.replace("value", Number(args.value).toFixed(2) + "%");
    } else {
      result = result.replace("value", args.value.toMeasureFormart(chart_opt.others.measureField.numberFormat));
    }
    return result;
  };
  var asixLabelFormatter = function (value) {
    var result = value;
    if (datamarkingopt && datamarkingmapping[opt.others.dimensionField.name]) {
      result = datamarkingmapping[opt.others.dimensionField.name].mapping[result];
    }
    return result;
  }
  const setOption = (opt) => {
    chart_opt = $.extend(chart_opt, opt);
    chart_opt.series.forEach(function (d) {
      d.label.normal.formatter = labelFormatter;
    });
    chart_opt.xAxis[0].axisLabel.formatter = asixLabelFormatter;
    myChart.setOption(chart_opt);
  }
  //响应点击事件
  myChart.on("click", function (args) {
    if (args.componentType === "series" && args.name) {
      const callData = [{
        field: chart_opt.others.dimensionField,
        value: [args.name]
      }];
      if (self.onselected) {
        self.onselected(callData);
      }
    }
  });

  if (opt) {
    setOption(opt);
  }
  this.setOption = setOption;

}


